package com.lz.timer.an.ddjobs.simple;

import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.lz.common.util.DateUtil;
import com.lz.timer.an.entity.DspCampaign;
import com.lz.timer.an.entity.DspOutdoorsInventory;
import com.lz.timer.an.entity.DspOutdoorsStall;
import com.lz.timer.an.entity.FinAccount;
import com.lz.timer.an.entity.FinBill;
import com.lz.timer.an.entity.FinUnitAccount;
import com.lz.timer.an.enums.CampaignStatusEnum;
import com.lz.timer.an.enums.DspOutdoorsStallStatusEnum;
import com.lz.timer.an.enums.FinBillTypeEnum;
import com.lz.timer.an.service.DspCampaignService;
import com.lz.timer.an.service.DspOutdoorsInventoryService;
import com.lz.timer.an.service.DspOutdoorsStallService;
import com.lz.timer.an.service.FinAccountService;
import com.lz.timer.an.service.FinBillService;
import com.lz.timer.an.service.FinUnitAccountService;

import lombok.extern.slf4j.Slf4j;

/**
 * 复审通过
 *
 * @author rench
 */
@Slf4j
public class StatisticalReExaminaPassJob implements SimpleJob {
	
	@Autowired
	private DspCampaignService dspCampaignService;
	
	@Autowired
	private DspOutdoorsStallService dspOutdoorsStallservice;
	
	@Autowired
	private DspOutdoorsInventoryService dspOutdoorsInventoryService;
	
	@Autowired
	private FinBillService finBillService;
	
	@Autowired
	private FinUnitAccountService finUnitAccountService;
	
	@Autowired
	private FinAccountService finAccountService;
	
    @Override
    public void execute(final ShardingContext context) {

        long threadId = Thread.currentThread().getId();

        int result = 0;
        // 当前分片
        int item = context.getShardingItem();      

        log.info("SIMPLE Thread:{}, ShardingContext:{}", threadId, context.toString());
        switch (item) {
        case 0:
             
             log.info("==========================begin=============================");
             log.info("++++++++++++++++复审通过 一天未投放+++++++++++++++++");
             
             //遍历 推广计划表   状态复审待上刊，  时间差一天。  记录推广计划中的  dsp_id
             //便利广告计划表。
             Map<String, Object> queryMap = new HashMap<String, Object>();
             String dateStr = DateUtil.formatDate(DateUtil.minusDays(new Date(), 1), "yyyy-MM-dd HH:mm:ss");
             
             queryMap.put("examina_pass_time", dateStr);
             queryMap.put("status", CampaignStatusEnum.TO_BE_PUBLISHED.getValue());
             List<DspCampaign> dspCampaignList = dspCampaignService.selectListByMap(queryMap);
             
             log.info("thread:{} 遍历 符合条件的推广计划dspCampaignList:{}", threadId, dspCampaignList);
             
             // 推广计划变更   未投放
             for (DspCampaign dspCampaign : dspCampaignList) {
            	 
            	 Long dspId = dspCampaign.getDsp_user_id();
            	 String campaignNoStr = dspCampaign.getCampaign_no();
            	 BigDecimal campaignSumVaule = new BigDecimal("0");
            	 
            	//查询用户账户表
            	 FinAccount finAccount = finAccountService.selectOneByPK(dspId);
            	 log.info("thread:{} 查询推广计划 广告主账户信息 dspCampaign:{}, finAccount:{}", threadId, dspCampaign, finAccount);
            	 
            	 dspCampaign.setStatus(CampaignStatusEnum.NOT_PUT_IN.getValue());
            	 dspCampaignService.update(dspCampaign);
            	 
            	 queryMap.clear();
            	 queryMap.put("campaign_no", campaignNoStr);
            	 queryMap.put("status", DspOutdoorsStallStatusEnum.FILING_STATUS.getValue());
            	 
            	List<DspOutdoorsStall> dspOutdoorsStallList = dspOutdoorsStallservice.selectListByMap(queryMap);
            	
            	log.info("thread:{} 查询推广计划下符合条件的占档信息 dspOutdoorsStallList:{}", threadId, dspOutdoorsStallList);
            	
            	for (DspOutdoorsStall dspOutdoorsStall : dspOutdoorsStallList) {
					
            		Long id = dspOutdoorsStall.getId();
            		dspOutdoorsStallservice.deleteByPK(id);
            		
            		queryMap.clear();
            		queryMap.put("udid", dspOutdoorsStall.getUdid());
            		queryMap.put("ssp_ad_slot_rtb_id", dspOutdoorsStall.getSsp_ad_slot_rtb_id());
            		
            		List<DspOutdoorsInventory> dspOutdoorsInventorieList = dspOutdoorsInventoryService.selectListByMap(queryMap);
            		
            		log.info("thread:{} 查询推广计划下符合条件的库存信息 dspOutdoorsInventorieList:{}", threadId, dspOutdoorsInventorieList);
            		for (DspOutdoorsInventory dspOutdoorsInventory : dspOutdoorsInventorieList) {
						
            			log.info("thread:{} 开始清库存， 清理前dspOutdoorsInventory:{}", threadId, dspOutdoorsInventory);
            			
            			Long inventory = dspOutdoorsInventory.getInventory();
            			Long occupy_inventory = dspOutdoorsInventory.getOccupy_inventory();
            			
            			dspOutdoorsInventory.setInventory(inventory + occupy_inventory);
            			dspOutdoorsInventory.setOccupy_inventory(0L);
            			
            			dspOutdoorsInventoryService.update(dspOutdoorsInventory);
					}
            		
				}
            	
            	//单元账户
            	queryMap.clear();
            	queryMap.put("campaign_no", campaignNoStr);
            	List<FinUnitAccount> finUnitAccountList = finUnitAccountService.selectListByMap(queryMap);
            	
            	log.info("thread:{} 查询推广计划下符合条件的单元账户信息 finUnitAccountList:{}", threadId, finUnitAccountList);
            	
            	for (FinUnitAccount finUnitAccount : finUnitAccountList) {
            		
            		BigDecimal frozenAmount = finUnitAccount.getFrozen_amount();
        			
        			finUnitAccount.setRefund(frozenAmount);
        			finUnitAccount.setFrozen_amount(new BigDecimal(0));
        			
        			finUnitAccountService.update(finUnitAccount);
        			
        			FinBill finBill = new FinBill();
        			finBill.setAccount_id(finUnitAccount.getId());
        			finBill.setAmount(frozenAmount);
        			finBill.setCash_surplus(frozenAmount.add(finAccount.getAmount()));
        			
					try {
						InetAddress addr = InetAddress.getLocalHost();
						finBill.setClient_ip(addr.getHostAddress());
					} catch (UnknownHostException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
        			
        			finBill.setCreate_user(0L);
        			finBill.setCreate_user_name("复审通过一天未投放");
        			finBill.setCreate_time(new Date());
        			finBill.setDetail_id(0L);
        			
        			finBill.setDsp_user_id(finAccount.getDsp_user_id());
        			finBill.setDsp_user_name(finAccount.getDsp_user_name());
        			finBill.setOper_type(FinBillTypeEnum.FROZEN_TYPE.getValue());
        			
        			log.info("thread:{} 新增单元账单信息 finBill:{}", threadId, finBill);
        			finBillService.insert(finBill);
        			
        			campaignSumVaule.add(frozenAmount);
				}
            	
            	BigDecimal frozenAmount = finAccount.getFrozen_amount();
            	BigDecimal amount = finAccount.getAmount();
            	
            	
            	finAccount.setAmount(amount.add(campaignSumVaule));
            	finAccount.setFrozen_amount(frozenAmount.subtract(campaignSumVaule));
            	
            	log.info("thread:{} 修改用户账户信息 finAccount:{}", threadId, finAccount);
            	finAccountService.update(finAccount);
			}
             
            log.info("====================+======end=================+============");
             
            break;
        default:
            log.warn("not total job, item:{}, Thread:{}", item, threadId);
            return;
        }

        log.info("job ：time = {} SIMPLE Thread:{}, result:{}, end", new Date(), threadId, result);

    }

}